package com.parleys.android.client.io;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.net.Uri;
import android.util.Log;

import com.parleys.android.client.provider.ParleysContract;
import com.parleys.android.client.provider.ParleysContract.Spaces;
import com.parleys.android.client.util.ParleysUriUtils;
import com.parleys.android.client.util.Sets;

public class SpacesHandler extends JSONHandler {
	
	private static final String TAG = "SpacesHandler";
	
	public SpacesHandler() {
		super(ParleysContract.CONTENT_AUTHORITY);
	}

	@Override
	public ArrayList<ContentProviderOperation> parse(JSONArray json, ContentResolver resolver) throws JSONException {
		final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
		final HashSet<Long> spaceIds = Sets.newHashSet();
		
		final int jsonSize = json.length();
		for (int i = 0; i < jsonSize; i++) {
			final JSONObject space = json.getJSONObject(i);
			final long spaceId = space.getLong("id");
			final long createdOn = space.getLong("createdOn");
			final long modifiedOn = space.getLong("modifiedOn");
			final String name = space.getString("name");
			final String description = space.getString("description");
			final String thumbnailUrl = ParleysUriUtils.removeLeadingSlashes(space.getString("thumbnailUrl"));
			final boolean isPublic = space.getBoolean("public");
			final boolean visibleIpad = space.getBoolean("visibleIpad");
			final long totalViewCount = space.getLong("totalViewCount");
			
			spaceIds.add(spaceId);
			
			final ContentProviderOperation.Builder operation = ContentProviderOperation.newInsert(Spaces.CONTENT_URI);
			operation.withValue(Spaces.SPACE_ID, spaceId)
				.withValue(Spaces.CREATED_ON, createdOn)
				.withValue(Spaces.MODIFIED_ON, modifiedOn)
				.withValue(Spaces.NAME, name)
				.withValue(Spaces.DESCRIPTION, description);
			if (thumbnailUrl != null && !isEmptyThumbnail(thumbnailUrl)) {
				operation.withValue(Spaces.THUMBNAIL_URL, thumbnailUrl);
			}
			operation.withValue(Spaces.PUBLIC, isPublic)
				.withValue(Spaces.VISIBLE_IPAD, visibleIpad)
				.withValue(Spaces.TOTAL_VIEWCOUNT, totalViewCount);
			batch.add(operation.build());
		}

    	HashSet<Long> lostSpaceIds = getLostIds(spaceIds, Spaces.CONTENT_URI, SpacesQuery.PROJECTION, SpacesQuery.SPACE_ID, resolver);
    	for (Iterator<Long> it = lostSpaceIds.iterator(); it.hasNext(); ) {
    		Long lostSpaceId = it.next();
	    	Uri deleteUri = Spaces.buildSpaceUri(lostSpaceId.intValue());
	    	batch.add(ContentProviderOperation.newDelete(deleteUri).build());
    	}
		
		return batch;
	}

	@Override
	public void notify(ContentProviderResult[] result, ContentResolver resolver) throws JSONException {
		if (result != null && result.length > 0) {
			Log.d(TAG, "Notifying data set changes for " + Spaces.CONTENT_URI);
			resolver.notifyChange(Spaces.CONTENT_URI, null);
		}
	}

    private interface SpacesQuery {
        String[] PROJECTION = {
                Spaces.SPACE_ID,
        };

        int SPACE_ID = 0;
    }

}
